package com.niiwoo.civet.account.service.local.check.job.apiservice.BackrollRecharge;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.civet.account.dao.entity.AccountBase;
import com.niiwoo.civet.account.dao.entity.AccountCheckingBackrollRecharge;
import com.niiwoo.civet.account.dao.entity.AccountCheckingException;
import com.niiwoo.civet.account.dao.entity.RollbackRechargeOrder;
import com.niiwoo.civet.account.dao.entity.WithdrawOrder;
import com.niiwoo.civet.account.dao.mapper.AccountBaseMapperExt;
import com.niiwoo.civet.account.dao.mapper.AccountCheckingBackrollRechargeMapperExt;
import com.niiwoo.civet.account.dao.mapper.AccountCheckingRollbackRechargeOrderMapperExt;
import com.niiwoo.civet.account.dao.mapper.WithdrawOrderMapperExt;
import com.niiwoo.civet.account.dto.request.AccountCheckingBackrollRechargeRequestDTO;
import com.niiwoo.civet.account.service.local.check.job.api.CheckDetailService;
import com.niiwoo.civet.account.service.local.check.job.api.ParseService;
import com.niiwoo.civet.account.service.local.check.job.enums.CheckResultEnum;
import com.niiwoo.civet.account.service.local.check.job.enums.HandleTypeEnum;
import com.niiwoo.civet.account.service.local.check.job.util.DateUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service(version = "1.0.0")
public class BackrollRechargeCheckDetailServiceImpl
		implements ParseService<AccountCheckingBackrollRecharge>, CheckDetailService<AccountCheckingBackrollRecharge> {

	@Autowired
	private AccountCheckingBackrollRechargeMapperExt accountCheckingBackrollRechargeMapperExt;
	@Autowired
	private WithdrawOrderMapperExt withdrawOrderMapperExt;
	@Autowired
	private AccountCheckingRollbackRechargeOrderMapperExt accountCheckingRollbackRechargeOrderMapperExt;
	@Autowired
	private AccountBaseMapperExt accountBaseMapperExt;

	@Override
	public List<AccountCheckingBackrollRecharge> load(Long checkRecordId, int page, int pageSize) {
		// shardingjdbc 强制走主库
		if (!HintManagerHolder.isMasterRouteOnly()) {
            HintManagerHolder.clear();
            HintManager hintManager = HintManager.getInstance();
            hintManager.setMasterRouteOnly();
        }

		log.debug("is matster route only : {}", HintManagerHolder.isMasterRouteOnly());

		AccountCheckingBackrollRechargeRequestDTO accountCheckingBackrollRechargeRequestDTO = new AccountCheckingBackrollRechargeRequestDTO();
		PageHelper.startPage(page, pageSize);
		accountCheckingBackrollRechargeRequestDTO.setCheckingRecordId(checkRecordId);
		accountCheckingBackrollRechargeRequestDTO.setStatus(Byte.valueOf("1"));
		List<AccountCheckingBackrollRecharge> accountCheckingBackrollRechargeList = accountCheckingBackrollRechargeMapperExt
				.queryCheckingBackrollRechargePage(accountCheckingBackrollRechargeRequestDTO);
		return accountCheckingBackrollRechargeList;
	}

	@Override
	public AccountCheckingException check(AccountCheckingBackrollRecharge accountCheckingBackrollRecharge,
			String checkDate) {
		List<String> errors = new ArrayList<String>();
		AccountCheckingException accountCheckingException = new AccountCheckingException();
		accountCheckingBackrollRecharge.setStatus(Byte.valueOf("2"));
		RollbackRechargeOrder rollbackRechargeOrder = accountCheckingRollbackRechargeOrderMapperExt.queryRollbackRechargeOrderByRequestNo(accountCheckingBackrollRecharge.getBackrollRequestNo());
		if(null == rollbackRechargeOrder){
			accountCheckingException.setHandleType(HandleTypeEnum.BACK_ONLY.getIndex());
			errors.add(CheckResultEnum.NO_RECORD.getName());
			return submit(accountCheckingBackrollRecharge, accountCheckingException, rollbackRechargeOrder, errors, checkDate);
		}
		if (accountCheckingBackrollRecharge.getWithdrawArrivalAmount().compareTo(rollbackRechargeOrder.getRollbackAmount()) != 0) { // 实际金额
			errors.add(CheckResultEnum.REAL_AMOUNT_NOT_EQUAL.getName());
			accountCheckingException.setHandleType(HandleTypeEnum.BOTH_ERROR.getIndex());
		}
		if (accountCheckingBackrollRecharge.getRechargeCommission().compareTo(rollbackRechargeOrder.getRollbackFee()) != 0) {
			errors.add(CheckResultEnum.FREE_AMOUNT_NOT_EQUAL.getName());
			accountCheckingException.setHandleType(HandleTypeEnum.BOTH_ERROR.getIndex());
		}

		WithdrawOrder withdrawOrder = withdrawOrderMapperExt.selectByPrimaryKey(rollbackRechargeOrder.getWithdrawOrderId());
		if(accountCheckingBackrollRecharge.getAmount().compareTo(withdrawOrder.getAmount()) != 0 ){
			errors.add(CheckResultEnum.AMOUNT_NOT_EQUAL.getName());
			accountCheckingException.setHandleType(HandleTypeEnum.BOTH_ERROR.getIndex());
		}
		if( !withdrawOrder.getRequestNo().equals(rollbackRechargeOrder.getWithdrawRequestNo())){
            errors.add(CheckResultEnum.REQUEST_NO_NOT_LINK.getName());
            accountCheckingException.setHandleType(HandleTypeEnum.BOTH_ERROR.getIndex());
        }

		//回充请求流水 backroll_request_no 业务逻辑需要理清
		//平台用户编号验证
		{
			AccountBase accountBase = accountBaseMapperExt.selectByPrimaryKey(rollbackRechargeOrder.getAccountId());
			if( !accountCheckingBackrollRecharge.getPlatformUserNo().equals(accountBase.getAccountNo())){
				errors.add(CheckResultEnum.PLATFORM_USER_NO_ERROR.getName());
				accountCheckingException.setHandleType(HandleTypeEnum.BOTH_ERROR.getIndex());
			}
		}


		return submit(accountCheckingBackrollRecharge, accountCheckingException, rollbackRechargeOrder, errors, checkDate);
	}

	private AccountCheckingException submit(AccountCheckingBackrollRecharge accountCheckingBackrollRecharge,
			AccountCheckingException accountCheckingException, RollbackRechargeOrder rollbackRechargeOrder, List<String> errors,
			String checkDate) {
		if (null != errors && errors.size() > 0) {
			accountCheckingException.setStatus(Byte.valueOf("1"));
			accountCheckingException.setBusinessType(accountCheckingBackrollRecharge.getBusinessType());
			accountCheckingException.setOrderNo(accountCheckingBackrollRecharge.getBackrollOrderNo());
			accountCheckingException.setCheckingType(Byte.valueOf("5"));
			accountCheckingException.setCheckingRecordId(accountCheckingBackrollRecharge.getCheckingRecordId());
			accountCheckingException.setCheckingDetailId(accountCheckingBackrollRecharge.getId());
			accountCheckingException.setPlatformRecordId(rollbackRechargeOrder == null ? null : rollbackRechargeOrder.getId());
			accountCheckingException.setCreateTime(new Date());
			accountCheckingException.setBillDate(checkDate);
			accountCheckingException.setDescription(errors.toString());
			accountCheckingBackrollRecharge.setRemark(errors.toString());
			
			return accountCheckingException;
		}
		return null;
	}

	@Override
	public AccountCheckingBackrollRecharge parse(Long recordId, String content) {
		// 0充值时间1平台商编2支付公司代码3回充请求流水号4回充订单编号5业务类型6金额7币种8会员编号
		// 9平台用户编号10支付方式11提现到账金额12提现佣金13备注14提现请求流水号
		if (content == null || "".equals(content))
			return null;
		String[] sArr = content.split(",");
		AccountCheckingBackrollRecharge record = new AccountCheckingBackrollRecharge();
		record.setRechargeTime(DateUtil.parseCheckDate(sArr[0]));
		record.setPlatformMerchantNo(sArr[1]);
		record.setPayChannelCode(sArr[2]);
		record.setBackrollRequestNo(sArr[3]);
		record.setBackrollOrderNo(sArr[4]);
		record.setBusinessType(Byte.valueOf(sArr[5]));
		record.setAmount(BigDecimal.valueOf(Double.valueOf(sArr[6])));
		record.setAmonnt("人民币"); //7-人民币
		record.setMemberNo(sArr[8]);
		record.setPlatformUserNo(sArr[9]);
		record.setPayType(Byte.valueOf(sArr[10]));
		record.setWithdrawArrivalAmount(BigDecimal.valueOf(Double.valueOf(sArr[11])));
		record.setRechargeCommission(BigDecimal.valueOf(Double.valueOf(sArr[12])));
		record.setRemark(sArr[13]);
		record.setRechargeRequestNo(sArr[14]);

		record.setStatus((byte) 1); // 1待处理
		record.setCheckingRecordId(recordId);
		return record;
	}

	@Override
	public void save(List<AccountCheckingBackrollRecharge> list) {
		if (list == null || list.isEmpty())
			return;
		// accountCheckingBackrollRechargeMapperExt.insertBatch(list);

		for (AccountCheckingBackrollRecharge accountCheckingBackrollRecharge : list) {
			accountCheckingBackrollRechargeMapperExt.insert(accountCheckingBackrollRecharge);
		}
	}

	@Override
	public void deleteCheckRecord(Long recordId) {
		accountCheckingBackrollRechargeMapperExt.deleteByCheckingRecordId(recordId);
	}

	@Override
	public void extendBusiness(Long checkRecordId) {
		//暂无业务
	}

	@Override
	public void batchUpdateCheckDetailStatus(Long checkRecordId, Byte status) {
		accountCheckingBackrollRechargeMapperExt.updateStatusByCheckingRecordId(checkRecordId, status);
	}

	@Override
	public void deleteAllCheckSuccessBankOrder(Long checkRecordId) {
		accountCheckingBackrollRechargeMapperExt.deleteByCheckingRecordId(checkRecordId);
	}
}
